﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FIX42FeedPlugin.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge.Plugins
{
    #region Using Directives

    using System;
    using System.Collections.Generic;

    using Org.OpenTrader.Framework.Enums;
    using Org.OpenTrader.Framework.Events;
    using Org.OpenTrader.Framework.Forge.Events;
    using Org.OpenTrader.Framework.Forge.Interfaces;
    using Org.OpenTrader.Framework.LiveObjects;
    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The fi x 42 feed plugin.
    /// </summary>
    [Credits("FIX42 Feed Plugin", "Handles all feed operations using FIX 4.2", "David Denis", "Copyright (C) David Denis <mailto:david.denis@systemathics.com>")]
    [ImplementsInterface("Org.OpenTrader.Framework.Forge.Interfaces.IFeedPlugin")]
    [ConfigurationField("SubscriptionConfigurationSchema", "Symbol", typeof(ConfigurationField.String), "Symbol", IsMandatory = true, DefaultValue = "Symbol")]
    public sealed partial class FIX42FeedPlugin : FixFeedPlugin
    {
        #region Constants and Fields

        /// <summary>
        /// The application.
        /// </summary>
        private MyApplication application;

        /// <summary>
        /// The Connection.
        /// </summary>
        private FIXConnection connection;

        /// <summary>
        /// Subscriptions id->i
        /// </summary>
        private IDictionary<string, Guid> requests;

        /// <summary>
        /// Subscriptions i->id
        /// </summary>
        private IDictionary<Guid, string> requestsReverse;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="FIX42FeedPlugin"/> class.
        /// </summary>
        /// <param name="descriptor">
        /// The descriptor.
        /// </param>
        /// <param name="container">
        /// The container.
        /// </param>
        public FIX42FeedPlugin(ILiveObjectDescriptor descriptor, ILiveObjectContainer container)
            : base(descriptor, container)
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Status.
        /// </summary>
        public override EConnectionStatus ConnectionStatus
        {
            get
            {
                return this.connection.ConnectionStatus;
            }
        }

        /// <summary>
        /// Gets ConnectionURL.
        /// </summary>
        public override string ConnectionURL
        {
            get
            {
                return this.connection.ToString();
            }
        }

        /// <summary>
        /// Gets EmitedEventsType.
        /// </summary>
        public override EEmitedEventsType EmitedEventsType
        {
            get
            {
                return EEmitedEventsType.QuoteEvents;
            }
        }

        /// <summary>
        /// Gets a value indicating whether NeedResubscriptionIfDisconnected.
        /// </summary>
        public override bool NeedResubscriptionIfDisconnected
        {
            get
            {
                return true;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The connect.
        /// </summary>
        /// <returns>
        /// </returns>
        public override Status Connect()
        {
            return this.connection.Connect();
        }

        /// <summary>
        /// The disconnect.
        /// </summary>
        /// <returns>
        /// </returns>
        public override Status Disconnect()
        {
            return this.connection.Disconnect();
        }

        /// <summary>
        /// The on activation context.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="activationEventArgs">
        /// The activation Context.
        /// </param>
        public override void OnActivation(object sender, ActivationEventArgs activationEventArgs)
        {
            if (activationEventArgs is ActivationEventArgs.CreateDestroy)
            {
                switch (activationEventArgs.Type)
                {
                    case EActivationType.Activation:
                        this.application = new MyApplication(this);
                        this.connection = new FIXConnection(
                            this, 
                            EFIXVersion.FIX42, 
                            EFIXPluginType.FIXOrderPlugin, 
                            this.application, 
                            (string)this.Configuration["Host"], 
                            (int)this.Configuration["Port"], 
                            (string)this.Configuration["SenderCompID"], 
                            (string)this.Configuration["TargetCompID"], 
                            (string)this.Configuration["ODBCConnectionString"]);
                        this.requests = new Dictionary<string, Guid>();
                        this.requestsReverse = new Dictionary<Guid, string>();
                        break;

                    case EActivationType.Desactivation:
                        break;
                }
            }
        }

        /// <summary>
        /// Send a "start subscription" request
        /// </summary>
        /// <param name="wiring">
        /// The wiring.
        /// </param>
        /// <param name="handler">
        /// The handler.
        /// </param>
        /// <returns>
        /// True on success, False otherwise
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public override Status StartSubscription(IFeedWiring wiring, RemotableEventHandler<FeedEventArgs> handler)
        {
            //// Already some subscription
            // if (requestsReverse.ContainsKey(info.InstrumentID))
            // return false;

            //// No Connection available
            // if (Connection.Status != EConnectionStatus.Connected)
            // return false;

            // MDReqID id = StartSubscription(
            // info.ObjectParameters["Symbol"] as string,
            // System.Guid.NewGuid().ToString(),
            // 5 /* TODO remove hardcoding */ );
            // if (id != null)
            // {
            // // Add request entries
            // requests[id.ToString()] = info.InstrumentID;
            // requestsReverse[info.InstrumentID] = id.ToString();
            // }

            // return id != null;
            throw new NotImplementedException();
        }

        /// <summary>
        /// Send a "stop subscription" request
        /// </summary>
        /// <param name="wiring">
        /// The wiring.
        /// </param>
        /// <param name="handler">
        /// The handler.
        /// </param>
        /// <returns>
        /// True on success, False otherwise
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public override Status StopSubscription(IFeedWiring wiring, RemotableEventHandler<FeedEventArgs> handler)
        {
            // if (Connection.Status != EConnectionStatus.Connected)
            // return false;

            //// Present
            // if (!RequestsReverse.ContainsKey(info.InstrumentID))
            // return false;

            // MDReqID id = StopSubscription(
            // info.ObjectParameters["Symbol"] as string,
            // requestsReverse[info.InstrumentID].Split(new char[] { ';' })[1], // note : Format is "symbol;key"
            // 5 /* TODO remove hardcoding */);

            // if (id != null)
            // {
            // // Remove requests
            // requests.Remove(id.ToString());
            // requestsReverse.Remove(info.InstrumentID);
            // }

            // return id != null;
            throw new NotImplementedException();
        }

        #endregion
    }
}